/*
This file is part of BORG.

    BORG is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    BORG is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BORG; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Copyright 2003 by Mike Berger
 */
/**
 * AddrListView class
 *
 * AddrListView contains functionality allowing the user to view all of their contacts
 * in a sortable table
 * @author Mike Berger
 * 
 * This class has been modified by UF Software Engineering Summer 2009
 * Developer: Darren Goldfarb
 */

package net.sf.borg.ui.address;

import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.swing.DefaultListSelectionModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;

import net.sf.borg.common.Errmsg;
import net.sf.borg.common.PrefName;
import net.sf.borg.common.Resource;
import net.sf.borg.model.AddressModel;
import net.sf.borg.model.beans.Address;
import net.sf.borg.ui.DockableView;
import net.sf.borg.ui.MultiView;
import net.sf.borg.ui.ResourceHelper;
import net.sf.borg.ui.util.PopupMenuHelper;
import net.sf.borg.ui.util.StripedTable;
import net.sf.borg.ui.util.TablePrinter;
import net.sf.borg.ui.util.TableSorter;

import javax.swing.event.*;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


// the AddrListView displays a list of the current todo items and allows the
// suer to mark them as done
public class AddrListView extends DockableView {

	private Collection<Address> addresses; // list of rows currently displayed

	private AddrListView() {

		super();
		addModel(AddressModel.getReference());

		this.setLayout(new GridBagLayout());
		// init the gui components
		initComponents();

		// the todos will be displayed in a sorted table with 2 columns -
		// data and todo text
		jTable1.setModel(new TableSorter(new String[] {
				Resource.getPlainResourceString("First"),
				Resource.getPlainResourceString("Last"),
				Resource.getPlainResourceString("Email"),
				Resource.getPlainResourceString("Screen_Name"),
				Resource.getPlainResourceString("Home_Phone"),
				Resource.getPlainResourceString("Work_Phone"),
				Resource.getPlainResourceString("Birthday"),
		/*Resource.getPlainResourceString("contact_group")*/}, new Class[] {
				java.lang.String.class, java.lang.String.class,
				java.lang.String.class, java.lang.String.class,
				java.lang.String.class, java.lang.String.class,
				java.util.Date.class, /*java.lang.String.class*/ }));

		refresh();

	}
	   /**
	    * Refreshes the table
	    *
	    * Method edited by UF Software Engineering, Summer 2009
	    * Developer: Dylan Moore
	    * Change Summary: Added Support for contact groups
	    */
	public void refresh() {
		/* UF SE 2009 - Start of Additions */
		String currentGroup = (String)groupBox.getItemAt(groupBox.getSelectedIndex());
		if(currentGroup.equals("All"))
		{
			AddressModel addrmod_ = AddressModel.getReference();

			try {
				addresses = addrmod_.getAddresses();
			} catch (Exception e) {
				Errmsg.errmsg(e);
				return;
			}
		}
		else {
			addresses = AddressModel.getReference().getAddressesByGroup(currentGroup);
			/* UF SE 2009 - End of Additions */
		}
		// init the table to empty
		TableSorter tm = (TableSorter) jTable1.getModel();
		tm.addMouseListenerToHeaderInTable(jTable1);
		tm.setRowCount(0);

		Iterator<Address> it = addresses.iterator();
		while (it.hasNext()) {
			Address r = it.next();

			try {

				// add the table row
				Object[] ro = new Object[7];
				ro[0] = r.getFirstName();
				ro[1] = r.getLastName();
				ro[2] = r.getEmail();
				ro[3] = r.getScreenName();
				ro[4] = r.getHomePhone();
				ro[5] = r.getWorkPhone();
				ro[6] = r.getBirthday();

				tm.addRow(ro);
				tm.tableChanged(new TableModelEvent(tm));
			} catch (Exception e) {
				Errmsg.errmsg(e);
				return;
			}

		}

		// sort the table by last name
		tm.sortByColumn(1);

	}

	private void editRow() {
		// figure out which row is selected.
		int index = jTable1.getSelectedRow();
		if (index == -1)
			return;
		jTable1.getSelectionModel().setSelectionInterval(index, index);
		// ensure only one row is selected.

		try {
			// need to ask the table for the original (before sorting) index of
			// the selected row
			TableSorter tm = (TableSorter) jTable1.getModel();
			int k = tm.getMappedIndex(index); // get original index - not
			// current sorted position in
			// tbl
			Object[] oa = addresses.toArray();
			Address addr = (Address) oa[k];

			MultiView.getMainView().addView(new AddressView(addr));
		} catch (Exception e) {
			Errmsg.errmsg(e);
		}
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	private ActionListener alAddNew, alEdit, alDelete;

    /**
	    * Initializes GUI components in AddrListView
	    *
	    * Method edited by UF Software Engineering, Summer 2009
	    * Developer: Dylan Moore, Darren Goldfarb
	    * Change Summary: Added components for contact groups
	    */
	private void initComponents()// GEN-BEGIN:initComponents
	{
		java.awt.GridBagConstraints gridBagConstraints;

		jScrollPane1 = new javax.swing.JScrollPane();
		jTable1 = new StripedTable();
		jPanel1 = new javax.swing.JPanel();
		newbutton = new javax.swing.JButton();
		jButton_email = new javax.swing.JButton();
		editbutton = new javax.swing.JButton();
		delbutton = new javax.swing.JButton();
		/* UF SE 2009 - Start of Additions */
		addGroupButton = new javax.swing.JButton();
		addGroupField = new javax.swing.JTextField(15);
		removeGroupButton = new javax.swing.JButton();
		/* UF SE 2009 - End of Additions */

		jScrollPane1.setPreferredSize(new java.awt.Dimension(554, 404));
		jTable1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(
				0, 0, 0)));
		// jTable1.setGridColor(java.awt.Color.blue);
		DefaultListSelectionModel mylsmodel = new DefaultListSelectionModel();
		mylsmodel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		jTable1.setSelectionModel(mylsmodel);
		jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jTable1MouseClicked(evt);
			}
		});
		jScrollPane1.setViewportView(jTable1);

		gridBagConstraints = new java.awt.GridBagConstraints();
		GridBagConstraints gridBagConstraints2 = new java.awt.GridBagConstraints();
		gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		gridBagConstraints.weightx = 5.0;
		gridBagConstraints.weighty = 2.0;
		add(jScrollPane1, gridBagConstraints);


		newbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource(
		"/resource/Add16.gif")));
		ResourceHelper.setText(newbutton, "Add_New");
		newbutton
		.addActionListener(alAddNew = new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				newbuttonActionPerformed(evt);
			}
		});

		jPanel1.add(newbutton);

		editbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource(
		"/resource/Edit16.gif")));
		ResourceHelper.setText(editbutton, "Edit");
		editbutton
		.addActionListener(alEdit = new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				editbuttonActionPerformed(evt);
			}
		});

		jPanel1.add(editbutton);

		delbutton.setIcon(new javax.swing.ImageIcon(getClass().getResource(
		"/resource/Delete16.gif")));
		ResourceHelper.setText(delbutton, "Delete");
		delbutton
		.addActionListener(alDelete = new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				delbuttonActionPerformed(evt);
			}
		});
		jPanel1.add(delbutton);


		jPanel1.add(jButton_email);
		jButton_email.setEnabled(false);  
		ResourceHelper.setText(jButton_email, "send_email_contact");
		
		jButton_email.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				onLaunchMail(evt);
			}

			private void onLaunchMail(ActionEvent evt) {

				String mailTo = "";
				if(((String) jTable1.getValueAt(selected[0], 2)).contains("@")) {
					mailTo = (String) jTable1.getValueAt(selected[0], 2);
				}
				for(int i = 1; i < selected.length; i++){
					if(((String) jTable1.getValueAt(selected[i], 2)).contains("@")) {
						if(!mailTo.equals("")) 
							mailTo = mailTo.concat(", ");
						mailTo = mailTo.concat((String) jTable1.getValueAt(selected[i], 2));
					}
				}
				Desktop desktop = Desktop.getDesktop(); 
				try {
					URI uriMailTo = new URI("mailto",mailTo,null);  //must use URI object when passing email address
					desktop.mail(uriMailTo);                		//open OS default mail application and pass email address      
				}
				catch(IOException ioe) {
					ioe.printStackTrace();
				} 
				catch(URISyntaxException use) {
					use.printStackTrace();
				} 
			}	

		});
		/* UF SE 2009 - Start of Additions */
		groupLabel = new JLabel();
		groupBox = new JComboBox();
		ResourceHelper.setText(groupLabel, "contact_group");

		groupBox.setBackground(Color.WHITE);
		groupBox.addItem("All");
		groupBox.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				//code for changing displayed contacts when group is changed
				String currGroup = (String)groupBox.getItemAt(groupBox.getSelectedIndex());

				/*
				//debug
				JOptionPane
				.showConfirmDialog(null, currGroup, null,
						JOptionPane.YES_NO_OPTION);
				//\debug
				 */

				ArrayList<Address> addrs = AddressModel.getReference().getAddressesByGroup(currGroup);
				addresses.clear();
				addresses = addrs;
				refresh();
			}

		});
		groupLabel.setLabelFor(groupBox);
		ResourceHelper.setText(addGroupButton, "Add_Contact_Group");
		addGroupButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				//code for creating new contact group
				
				//first check to see if the groupField is non-empty, or if the entry already exists
				if (addGroupField.getText().compareTo("") == 0) {
					return;
				}
				for ( int i = 0; i < groupBox.getItemCount(); i++ ) {
					if ( groupBox.getItemAt(i).toString().compareTo(addGroupField.getText())== 0) {
						//group found, don't continue execution
						addGroupField.setText("");
						return;  
					}
				}
				AddressModel addrMod = AddressModel.getReference();
				addrMod.saveGroup(addGroupField.getText());
				updateComboBox();
				addGroupField.setText("");

			}			
		});
		ResourceHelper.setText(removeGroupButton, "Remove_Selected_Group");
		removeGroupButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
			//code for removing contact group
			AddressModel addrMod = AddressModel.getReference();
			addrMod.removeGroup((String)groupBox.getSelectedItem());
			updateComboBox();
		}

			
	});

		addGroupField.setSize(250, 12);
		addGroupField.setHorizontalAlignment(JTextField.LEFT);

		populateGroups();
		jPanel1.add(removeGroupButton);
		jPanel1.add(groupLabel);
		jPanel1.add(groupBox);
		jPanel1.add(addGroupButton);
		jPanel1.add(addGroupField);
		
		/* UF SE 2009 - End of Additions */

		
		AddressModel addrmod_ = AddressModel.getReference();	//start...copied from original source
		try {
			addresses = addrmod_.getAddresses();
		} catch (Exception e) {
			Errmsg.errmsg(e);
			return;
		}
		Iterator<Address> it = addresses.iterator();	//end...copied from original source


		//AddressModel addrmod_ = AddressModel.getReference();	//start...copied from original source
		try {
			addresses = addrmod_.getAddresses();
		} catch (Exception e) {
			Errmsg.errmsg(e);
			return;
		}
		//Iterator<Address> it = addrs_.iterator();	//end...copied from original source
		
		/* UF SE 2009 - Start of Additions */
		int i = 0;			
		while (it.hasNext()) {
			it.next();
			i++;
		}	
		ListSelectionEvent e = new javax.swing.event.ListSelectionEvent(jTable1, 0, i, true);
		AddrListSelectionListener alsl = new AddrListSelectionListener();
		jTable1.getSelectionModel().addListSelectionListener(alsl);		
		/* UF SE 2009 - Start of Additions */


		

		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
		add(jPanel1, gridBagConstraints);

		new PopupMenuHelper(jTable1, new PopupMenuHelper.Entry[] {
				new PopupMenuHelper.Entry(alAddNew, "Add_New"),
				new PopupMenuHelper.Entry(alEdit, "Edit"),
				new PopupMenuHelper.Entry(alDelete, "Delete"), });
		
		

	}// GEN-END:initComponents
	 /**
	    * This method populates the group ComboBox with the groups stored in the database
	    * Method created by UF Software Engineering Summer 2009
	    * Developer: Dylan Moore
	    */
	public void populateGroups() {
		//code for populating group combobox
		ArrayList<String> theGroups = AddressModel.getReference().getGroups();
		for(String group : theGroups)
		{
			groupBox.addItem(group);
		}
	}

	private void delbuttonActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_delbuttonActionPerformed
	{// GEN-HEADEREND:event_delbuttonActionPerformed
		// figure out which row is selected to be marked as done
		int[] indices = jTable1.getSelectedRows();
		if (indices.length == 0)
			return;

		int ret = JOptionPane.showConfirmDialog(null, Resource
				.getResourceString("Delete_Addresses"), Resource
				.getPlainResourceString("Delete"),
				JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
		if (ret != JOptionPane.OK_OPTION)
			return;

		AddressModel amod = AddressModel.getReference();
		for (int i = 0; i < indices.length; ++i) {
			int index = indices[i];
			try {
				// need to ask the table for the original (before sorting) index
				// of the selected row
				TableSorter tm = (TableSorter) jTable1.getModel();
				int k = tm.getMappedIndex(index); // get original index - not
				// current sorted position
				// in tbl
				Object[] oa = addresses.toArray();
				Address addr = (Address) oa[k];
				amod.delete(addr);
			} catch (Exception e) {
				Errmsg.errmsg(e);
			}
		}

		amod.refresh();
	}// GEN-LAST:event_delbuttonActionPerformed

	private void jTable1MouseClicked(java.awt.event.MouseEvent evt)// GEN-FIRST:event_jTable1MouseClicked
	{// GEN-HEADEREND:event_jTable1MouseClicked
		if (evt.getClickCount() < 2)
			return;
		editRow();
	}// GEN-LAST:event_jTable1MouseClicked

	private void editbuttonActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_editbuttonActionPerformed
	{// GEN-HEADEREND:event_editbuttonActionPerformed
		editRow();
	}// GEN-LAST:event_editbuttonActionPerformed

	private void newbuttonActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_newbuttonActionPerformed
	{// GEN-HEADEREND:event_newbuttonActionPerformed
		Address addr = AddressModel.getReference().newAddress();
		addr.setKey(-1);
		MultiView.getMainView().addView(new AddressView(addr));
	}// GEN-LAST:event_newbuttonActionPerformed

	private void printListActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_printListActionPerformed

		// user has requested a print of the table
		try {
			TablePrinter.printTable(jTable1);
		} catch (Exception e) {
			Errmsg.errmsg(e);
		}
	}// GEN-LAST:event_printListActionPerformed

	private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_exitMenuItemActionPerformed
		this.fr_.dispose();
	}// GEN-LAST:event_exitMenuItemActionPerformed

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton delbutton;

	private javax.swing.JButton editbutton;

	private javax.swing.JPanel jPanel1;

	private javax.swing.JScrollPane jScrollPane1;

	private StripedTable jTable1;

	private javax.swing.JButton newbutton;
	
	/* UF SE 2009 - Start of Additions */
	private javax.swing.JButton jButton_email;

	private javax.swing.JComboBox groupBox;

	private javax.swing.JLabel groupLabel;

	private javax.swing.JButton addGroupButton;

	private javax.swing.JTextField addGroupField;
	
	private javax.swing.JButton removeGroupButton;
	
	private int selected[];
	
	/* UF SE 2009 - End of Additions */
	public PrefName getFrameSizePref() {
		return PrefName.ADDRLISTVIEWSIZE;
	}

	public String getFrameTitle() {
		return Resource.getPlainResourceString("Address_Book");
	}

	public JMenuBar getMenuForFrame() {

		JMenuBar menuBar = new javax.swing.JMenuBar();
		JMenu fileMenu = new javax.swing.JMenu();
		JMenuItem printList = new javax.swing.JMenuItem();
		JMenuItem exitMenuItem = new javax.swing.JMenuItem();

		ResourceHelper.setText(fileMenu, "Action");

		JMenuItem mnuitm = new JMenuItem();
		ResourceHelper.setText(mnuitm, "Add_New");
		mnuitm.setIcon(newbutton.getIcon());
		mnuitm.addActionListener(alAddNew);
		fileMenu.add(mnuitm);

		mnuitm = new JMenuItem();
		ResourceHelper.setText(mnuitm, "Edit");
		mnuitm.setIcon(editbutton.getIcon());
		mnuitm.addActionListener(alEdit);
		fileMenu.add(mnuitm);

		mnuitm = new JMenuItem();
		ResourceHelper.setText(mnuitm, "Delete");
		mnuitm.setIcon(delbutton.getIcon());
		mnuitm.addActionListener(alDelete);
		fileMenu.add(mnuitm);

		ResourceHelper.setText(printList, "Print_List");
		printList.setIcon(new ImageIcon(getClass().getResource(
		"/resource/Print16.gif")));
		printList.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				printListActionPerformed(evt);
			}
		});

		fileMenu.add(printList);

		ResourceHelper.setText(exitMenuItem, "Exit");
		exitMenuItem.setIcon(new ImageIcon(getClass().getResource(
		"/resource/Stop16.gif")));
		exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitMenuItemActionPerformed(evt);
			}
		});

		menuBar.add(fileMenu);


		fileMenu.add(exitMenuItem);

		return menuBar;

	}



	private static AddrListView singleton = null;

	public static AddrListView getReference() {
		if (singleton == null || !singleton.isDisplayable())
			singleton = new AddrListView();
		return (singleton);
	}
    /**
	    * This method refreshes the group ComboBox
	    *
	    * Method created by UF Software Engineering Summer 2009
	    * Developer: Darren Goldfarb, Jubal Ledden
	    */ 
	public void updateComboBox() {
		for(int i = groupBox.getItemCount()-1; i >= 1; i--){
			groupBox.removeItemAt(i);
		}
		populateGroups();
	}


	class AddrListSelectionListener implements ListSelectionListener {

		AddrListSelectionListener() {		}

		public void valueChanged(ListSelectionEvent e) {

			selected = jTable1.getSelectedRows();

			jButton_email.setEnabled(false);  
			Desktop desktop1 = Desktop.getDesktop();                //create Desktop object to check if supported


			for(int i = 0; i < selected.length; i++){

				if(((String) jTable1.getValueAt(selected[i], 2)).contains("@")) {   
					if (desktop1.isSupported(Desktop.Action.MAIL)) {//if Desktop is supported then enable button
						jButton_email.setEnabled(true);
					}

			}
		}
	}
}
}
